package com.xy.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

public class DemoSocketClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("server response: " + ctx.channel().remoteAddress());
//        ctx.channel().writeAndFlush("from client: " + System.currentTimeMillis());
//        TimeUnit.MILLISECONDS.sleep(5000);
        for (int i = 0; i < 1000; i++) {
            ByteBuf buf = getByteBuf(ctx, i + ":你好，我的名字是1234567!\n");
            ctx.channel().writeAndFlush(buf);
        }
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx, String msg) {
        byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes(bytes);
        return buffer;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
